package com.hrvsr.session.cookie;

import com.hrvsr.common.Request;
import com.hrvsr.common.redis.JedisHolder;
import com.hrvsr.common.util.PropertyUtil;
import com.hrvsr.common.util.SerializationUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

public class RedisCookiesPool implements CookiesPool {
	private static final long serialVersionUID = 203L;
	private static final String cookiesQueue = PropertyUtil.getProperty("cookie.redis.queue");
	@Override
	public Cookies poll(Request request) {
		//ignore request
		Jedis jedis = getJedis();
		try{
			Transaction trans = jedis.multi();
			Response<String> cookiesUuid = trans.rpoplpush(cookiesQueue, cookiesQueue);
			Response<byte[]> bytes = trans.get(cookiesUuid.get().getBytes());
			trans.exec();
			return SerializationUtil.unSerialize(bytes.get(), Cookies.class);
		} finally {
			jedis.close();
		}
	}

	@Override
	public void offer(Request request, Cookies cookies) {
		//ignore request
		String cookiesUuid = cookies.getCookiesUuid();
		Jedis jedis = getJedis();
		try{
			byte[] bytes = SerializationUtil.serialize(cookies);
			jedis.set(cookiesUuid.getBytes(), bytes);
		} finally {
			jedis.close();
		}
	}

	private Jedis getJedis() {
		Integer dbNo = Integer.valueOf(PropertyUtil.getProperty("cookie.redis.dbNo"));
		return JedisHolder.getJedisFromPool(dbNo);
	}

}
